import api from './api';
import { AxiosResponse } from 'axios';

// 通知类型枚举
export enum NotificationType {
  ANNOUNCEMENT = 'ANNOUNCEMENT',
  NOTICE = 'NOTICE',
  NEWS = 'NEWS',
}

// 目标角色枚举
export enum TargetRole {
  ALL = 'ALL',
  TEACHER = 'TEACHER',
  PARENT = 'PARENT'
}

// 通知状态枚举
export enum NotificationStatus {
  DRAFT = 'DRAFT',
  PUBLISHED = 'PUBLISHED',
  REVOKED = 'REVOKED'
}

// 附件类型
export interface Attachment {
  id: number;
  fileName: string;
  fileUrl: string;
  fileSize: number;
  fileType: string;
  uploadTime: string;
}

// 发布者类型
export interface Publisher {
  id: number;
  name: string;
  avatar?: string;
  role?: string;
}

// 班级信息类型
export interface ClassInfo {
  id: number;
  name: string;
  grade: string;
}

// 通知类型
export interface Notification {
  id: number;
  title: string;
  content: string;
  type: NotificationType;
  targetRole: TargetRole;
  isTop: boolean;
  status: NotificationStatus;
  publisher: Publisher;
  classInfo?: ClassInfo;
  coverImage?: string;
  attachments?: Attachment[];
  readCount?: number;
  createTime: string;
  updateTime?: string;
}

// 分页响应接口
export interface PageResponse<T> {
  content: T[];
  pageable: {
    pageNumber: number;
    pageSize: number;
    sort: {
      empty: boolean;
      sorted: boolean;
      unsorted: boolean;
    };
    offset: number;
    paged: boolean;
    unpaged: boolean;
  };
  last: boolean;
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  sort: {
    empty: boolean;
    sorted: boolean;
    unsorted: boolean;
  };
  numberOfElements: number;
  first: boolean;
  empty: boolean;
}

// 查询参数类型
export interface NotificationQueryParams {
  type?: NotificationType;
  targetRole?: TargetRole;
  classId?: number;
  status?: NotificationStatus;
  page?: number;
  size?: number;
}

// 创建通知参数类型
export interface CreateNotificationParams {
  title: string;
  content: string;
  type: NotificationType;
  targetRole: TargetRole;
  isTop?: boolean;
  status?: NotificationStatus;
  publisher: {
    id: number;
  };
  classInfo?: {
    id: number;
  };
}

// 更新通知参数类型
export interface UpdateNotificationParams {
  title?: string;
  content?: string;
  type?: NotificationType;
  targetRole?: TargetRole;
  isTop?: boolean;
  status?: NotificationStatus;
  classInfo?: {
    id: number;
  };
}

// API响应格式
interface ApiResponse<T> {
  status: string;
  message: string;
  data: T;
}

/**
 * 获取通知列表
 * @param params 查询参数
 * @returns 通知列表分页数据
 */
export const getNotifications = async (params: NotificationQueryParams = {}): Promise<PageResponse<Notification>> => {
  try {
    const { page = 0, size = 10, type, targetRole, classId, status } = params;
    const queryParams = {
      page,
      size,
      type,
      targetRole,
      classId,
      ...(status && { status }) // 只有当status有值时才添加到查询参数中
    };

    const response = await api.get<any>('/notifications', {
      params: queryParams
    });
    
    console.log('获取通知列表数据:', response.data);
    
    // 处理不同的响应格式
    if (response.data && response.data.data) {
      // 如果是标准API响应格式
      return response.data.data;
    } else if (response.data && response.data.content) {
      // 如果直接返回分页对象
      return response.data;
    } else {
      console.warn('通知列表数据格式不符合预期');
      return {
        content: [],
        pageable: {
          pageNumber: page,
          pageSize: size,
          sort: { empty: true, sorted: false, unsorted: true },
          offset: page * size,
          paged: true,
          unpaged: false
        },
        last: true,
        totalElements: 0,
        totalPages: 0,
        size: size,
        number: page,
        sort: { empty: true, sorted: false, unsorted: true },
        numberOfElements: 0,
        first: true,
        empty: true
      };
    }
  } catch (error) {
    console.error('获取通知列表失败:', error);
    throw error;
  }
};

/**
 * 获取通知详情
 * @param id 通知ID
 * @returns 通知详情
 */
export const getNotificationDetail = async (id: number): Promise<Notification> => {
  try {
    const response = await api.get<ApiResponse<Notification>>(`/notifications/${id}`);
    console.log('获取通知详情:', response);
    return response.data.data;
  } catch (error) {
    console.error('获取通知详情失败:', error);
    throw error;
  }
};

/**
 * 创建通知
 * @param params 创建参数
 * @returns 创建的通知
 */
export const createNotification = async (params: CreateNotificationParams): Promise<Notification> => {
  try {
    console.log('创建通知API - 参数:', params);
    const response = await api.post<ApiResponse<Notification>>('/notifications', params);
    console.log('创建通知API响应:', response.data);
    return response.data.data;
  } catch (error) {
    console.error('创建通知失败:', error);
    throw error;
  }
};

/**
 * 发布带附件的通知
 * @param params 通知参数
 * @param attachments 附件文件列表
 * @param coverImage 封面图片
 * @returns 创建的通知
 */
export const createNotificationWithFiles = async (
  params: CreateNotificationParams,
  attachments?: File[],
  coverImage?: File
): Promise<Notification> => {
  try {
    const formData = new FormData();
    
    // 添加通知数据
    formData.append('notification', JSON.stringify(params));
    
    // 添加附件
    if (attachments && attachments.length > 0) {
      attachments.forEach(file => {
        formData.append('attachments', file);
      });
    }
    
    // 添加封面图片
    if (coverImage) {
      formData.append('coverImage', coverImage);
    }
    
    const response = await api.post<ApiResponse<Notification>>('/notifications/with-files', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    console.log('创建带附件通知结果:', response);
    return response.data.data;
  } catch (error) {
    console.error('创建带附件通知失败:', error);
    throw error;
  }
};

/**
 * 更新通知
 * @param id 通知ID
 * @param params 更新参数
 * @returns 更新后的通知
 */
export const updateNotification = async (id: number, params: UpdateNotificationParams): Promise<Notification> => {
  try {
    console.log(`更新通知API - ID: ${id}, 参数:`, params);
    const response = await api.put<ApiResponse<Notification>>(`/notifications/${id}`, params);
    console.log('更新通知API响应:', response.data);
    return response.data.data;
  } catch (error) {
    console.error('更新通知失败:', error);
    throw error;
  }
};

/**
 * 更新带附件的通知
 * @param id 通知ID
 * @param params 更新参数
 * @param attachments 附件文件列表
 * @param coverImage 封面图片
 * @returns 更新后的通知
 */
export const updateNotificationWithFiles = async (
  id: number,
  params: UpdateNotificationParams,
  attachments?: File[],
  coverImage?: File
): Promise<Notification> => {
  try {
    const formData = new FormData();
    
    // 添加通知数据
    formData.append('notification', JSON.stringify(params));
    
    // 添加附件
    if (attachments && attachments.length > 0) {
      attachments.forEach(file => {
        formData.append('attachments', file);
      });
    }
    
    // 添加封面图片
    if (coverImage) {
      formData.append('coverImage', coverImage);
    }
    
    const response = await api.put<ApiResponse<Notification>>(`/notifications/${id}/with-files`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    console.log('更新带附件通知结果:', response);
    return response.data.data;
  } catch (error) {
    console.error('更新带附件通知失败:', error);
    throw error;
  }
};

/**
 * 删除通知
 * @param id 通知ID
 * @returns 是否删除成功
 */
export const deleteNotification = async (id: number): Promise<boolean> => {
  try {
    console.log(`删除通知API - ID: ${id}`);
    const response = await api.delete<ApiResponse<boolean>>(`/notifications/${id}`);
    console.log('删除通知API响应:', response.data);
    //完整数据格式就是data，无需修复，爆红是因为ApiResponse封装的问题
    return response.data;
  } catch (error) {
    console.error('删除通知失败:', error);
    throw error;
  }
};

/**
 * 设置通知置顶状态
 * @param id 通知ID
 * @param isTop 是否置顶
 * @returns 更新后的通知
 */
export const setNotificationTopStatus = async (id: number, isTop: boolean): Promise<Notification> => {
  try {
    console.log(`设置通知置顶状态API - ID: ${id}, 置顶状态: ${isTop}`);
    const response = await api.put<ApiResponse<Notification>>(`/notifications/${id}/top`, { isTop });
    console.log('设置通知置顶状态API响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('设置通知置顶状态失败:', error);
    throw error;
  }
};

/**
 * 更新通知状态
 * @param id 通知ID
 * @param status 通知状态
 * @returns 更新后的通知
 */
export const updateNotificationStatus = async (id: number, status: NotificationStatus): Promise<Notification> => {
  try {
    const response = await api.put<ApiResponse<Notification>>(`/notifications/${id}/status`, null, {
      params: { status }
    });
    console.log('更新通知状态结果:', response);
    return response.data;
  } catch (error) {
    console.error('更新通知状态失败:', error);
    throw error;
  }
};

/**
 * 获取置顶通知列表
 * @param status 通知状态，默认为PUBLISHED
 * @returns 置顶通知列表
 */
export const getTopNotifications = async (status: NotificationStatus = NotificationStatus.PUBLISHED): Promise<Notification[]> => {
  try {
    const response = await api.get<ApiResponse<Notification[]>>('/notifications/top', {
      params: { status }
    });
    console.log('获取置顶通知列表:', response);
    return response.data;
  } catch (error) {
    console.error('获取置顶通知列表失败:', error);
    throw error;
  }
};

/**
 * 搜索通知
 * @param title 标题关键字
 * @param status 通知状态，默认为PUBLISHED
 * @param page 页码，默认0
 * @param size 每页大小，默认10
 * @returns 通知分页列表
 */
export const searchNotifications = async (
  title: string,
  status: NotificationStatus = NotificationStatus.PUBLISHED,
  page: number = 0,
  size: number = 10
): Promise<PageResponse<Notification>> => {
  try {
    const response = await api.get<any>('/notifications/search', {
      params: { title, status, page, size }
    });
    
    console.log('搜索通知结果:', response);
    
    // 处理不同的响应格式
    if (response.data && response.data.data) {
      // 如果是标准API响应格式
      return response.data.data;
    } else if (response.data && response.data.content) {
      // 如果直接返回分页对象
      return response.data;
    } else {
      console.warn('搜索通知数据格式不符合预期');
      return {
        content: [],
        pageable: {
          pageNumber: page,
          pageSize: size,
          sort: { empty: true, sorted: false, unsorted: true },
          offset: page * size,
          paged: true,
          unpaged: false
        },
        last: true,
        totalElements: 0,
        totalPages: 0,
        size: size,
        number: page,
        sort: { empty: true, sorted: false, unsorted: true },
        numberOfElements: 0,
        first: true,
        empty: true
      };
    }
  } catch (error) {
    console.error('搜索通知失败:', error);
    throw error;
  }
}; 